package zzxkj.blog.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import zzxkj.blog.common.lang.Consts;
import zzxkj.blog.pojo.User;
import zzxkj.blog.service.UserService;

import javax.servlet.http.HttpSession;

/**
 * @author zzxkj
 */
@Controller
public class RegisterController {
    @Autowired
    HttpSession session;

    @Autowired
    UserService userService;
    @GetMapping("/register")
    public String RegisterPage(){
        return "register";
    }

    @PostMapping("/register")
    public String RegisterCommit(@RequestParam String nickname,
                                 @RequestParam String username,
                                 @RequestParam String password,
                                 @RequestParam String email,
                                 @RequestParam String captcha,
                                 RedirectAttributes attributes){
        if (nickname == null) {
            attributes.addFlashAttribute("message","昵称不能为空");
            return "redirect:/register";
        } else if (username == null) {
            attributes.addFlashAttribute("message","用户名不能为空");
            return "redirect:/register";
        } else if (captcha==null){
            attributes.addFlashAttribute("message","验证码不能为空");
            return "redirect:/register";
        } else if(!captcha.equals(session.getAttribute(Consts.CAPTCHA_SESSION_KEY))){
            attributes.addFlashAttribute("message","验证码错误");
            return "redirect:/register";
        } else if(email == null){
            attributes.addFlashAttribute("message","邮箱不能为空");
            return "redirect:/register";
        }
        if(userService.queryByNickname(nickname) != null){
            attributes.addFlashAttribute("message","昵称已存在");
            return "redirect:/register";
        }
        if(userService.queryByUsername(username) != null){
            attributes.addFlashAttribute("message","用户名已存在");
            return "redirect:/register";
        }
        //填充用户信息
        User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        user.setPassword(password);
        user.setEmail(email);
        Integer res = userService.createUser(user);
        if (res == null || res <= 0){
            attributes.addFlashAttribute("message","用户创建失败，请重试！");
            return "redirect:/register";
        }
        return "redirect:/";
    }
}
